package com.util;


import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

/**
 * @author 冥尘
 * 信息发送类
 */

public class SendMess {
    /**
     * 发送邮件
     * @param to 收件人邮箱
     * @param vcode 邮件内容
     */
    public static void sendMail(String to, String vcode) {
        SimpleEmail simpleEmail = new SimpleEmail();
        //开启SSL加密
        simpleEmail.setSSLOnConnect(false);
        //SMTP服务器的端口
        simpleEmail.setSslSmtpPort("465");
        //SMTP服务器的名字
        simpleEmail.setHostName("smtp.qq.com");
        //发件人邮箱以及授权码
        simpleEmail.setAuthentication("2959032098@qq.com", "cdbvaipghpjjdeai");
        //编码集
        simpleEmail.setCharset("UTF-8");
        try {
            //收件人邮箱
            simpleEmail.addTo(to);
            //发件人邮箱以及发件人名称
            simpleEmail.setFrom("2959032098@qq.com", "BhSyCase考试网:");
            //邮件主题
            simpleEmail.setSubject("BhSyCase考试网验证码");
            //邮件内容
            simpleEmail.setMsg(vcode);
            simpleEmail.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送短信
     * @param to 收件人手机号
     * @param vcode 短信内容
     * @throws Exception
     */
    public static void sendMessage(String to,String vcode) throws Exception{
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("http://utf8.api.smschinese.cn");
        post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//在头文件中设置转码
        NameValuePair[] data ={ new NameValuePair("Uid", "GGAlsobeetwn"),new NameValuePair("Key", "d41d8cd98f00b204e980"),new NameValuePair("smsMob",to),new NameValuePair("smsText","【bysy考试网】"+vcode)};
        post.setRequestBody(data);

        client.executeMethod(post);
        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        System.out.println("statusCode:"+statusCode);
        for(Header h : headers)
        {
            System.out.println(h.toString());
        }
        String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
        System.out.println(result); //打印返回消息状态

        post.releaseConnection();
    }
}
